<?php
// 二维码
// https://developers.weixin.qq.com/doc/offiaccount/Account_Management/Generating_a_Parametric_QR_Code.html

namespace JyWxThird\Init\Mp;

use JyWxThird\Kernel\Http;

trait Qrcode
{
  /**
   * 创建永久二维码
   *
   * @param int|string $value 二维码值
   * @return mixed
   */
  public function qrcodeCreate($value)
  {
    $param = [
      'action_name' => is_numeric($value) ? 'QR_LIMIT_SCENE' : 'QR_LIMIT_STR_SCENE',
    ];
    if (is_numeric($value)) {
      $param['action_info']['scene']['scene_id'] = $value;
    } else {
      $param['action_info']['scene']['scene_str'] = $value;
    }
    $url = $this->domainUrl . "/cgi-bin/qrcode/create?access_token=" . $this->get_access_token();
    $res = Http::httpPostJson($url, $param);
    if (isset($res['ticket'])) {
      $res['ticket_url'] = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . $res['ticket'];
      return $res;
    }
    
    $this->setError($res);
    return false;
  }
  
  /**
   * 创建临时二维码
   *
   * @param int|string $value  二维码值
   * @param int        $expire 二维码有效时间，单位(秒)。 最大不超过2592000（即30天），留空为2592000秒(30天)
   * @return mixed
   */
  public function qrcodeCreateTemp($value, $expire = 2592000)
  {
    $param = [
      'expire_seconds' => $expire,
      'action_name'    => is_numeric($value) ? 'QR_SCENE' : 'QR_STR_SCENE',
    ];
    if (is_numeric($value)) {
      $param['action_info']['scene']['scene_id'] = $value;
    } else {
      $param['action_info']['scene']['scene_str'] = $value;
    }
    $url = $this->domainUrl . "/cgi-bin/qrcode/create?access_token=" . $this->get_access_token();
    $res = Http::httpPostJson($url, $param);
    
    if (isset($res['ticket'])) {
      $res['ticket_url'] = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . $res['ticket'];
      return $res;
    }
    
    $this->setError($res);
    return false;
  }
}
